package com.iteaj.iboot.plugin.crawler.websocket;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iteaj.framework.spring.SpringUtils;
import com.iteaj.iboot.plugin.crawler.service.ISiteContentService;
import com.iteaj.iboot.plugin.crawler.service.ISitesService;
import com.iteaj.iboot.plugin.crawler.sites.ResolverParam;
import com.iteaj.iboot.plugin.crawler.sites.SiteResolver;
import com.iteaj.iboot.plugin.crawler.sites.SiteResolverManager;
import com.iteaj.iboot.plugin.crawler.sites.buyin.BuyinResolver;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
@ServerEndpoint("/crawler/ws/data")
public class CrawlerDataWebsocketHandler implements ApplicationContextAware {

    private static ISitesService sitesService;
    private static ISiteContentService siteContentService;

    @OnOpen
    public void onOpen(Session session) {

    }

    @OnMessage
    public void onMessage(Session session, String message) throws Exception {
        if(StrUtil.isNotBlank(message)) {
            JSONObject jsonObject = JSON.parseObject(message);
            ResolverParam param = ResolverParam.build(jsonObject);
            SiteResolver siteResolver = SiteResolverManager.get(param.getAlias());
            if(siteResolver != null) {
                siteResolver.resolve(param);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        sitesService = applicationContext.getBean(ISitesService.class);
        siteContentService = applicationContext.getBean(ISiteContentService.class);
    }
}
